package com.mlnx.work.config;

import com.mlnx.work.cache.CacheKeys;
import com.mlnx.work.properties.WorkProperties;

import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.shan.spring.cache.config.KeyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by amanda.shan on 2019/8/8.
 */
@Configuration
public class WorkCacheConfig {

    @Autowired
    private WorkProperties workProperties;

    class SupportL1Config implements KeyConfig {

        private String key;
        private Integer size;
        private int ttl = -1;   // 不设置超时时间 单位是s

        public SupportL1Config(String key, Integer size) {
            this.key = key;
            this.size = size;
        }

        public SupportL1Config(String key, Integer size, int ttl) {
            this.key = key;
            this.size = size;
            this.ttl = ttl;
        }

        @Override
        public CacheConfigurationBuilder<String, Object> getEhcacheBuilder() {

            if (size > 0) {
                // 限制缓存最大数量
                return cacheConfigurationBuilder(ResourcePoolsBuilder.heap(size));
            } else {
                // 不限制数量
                return cacheConfigurationBuilder(ResourcePoolsBuilder.heap(Integer.MAX_VALUE));
            }
        }

        @Override
        public String getKey() {
            return key;
        }

        @Override
        public boolean supportL2() {
            return false;
        }

        @Override
        public int timeToL2LiveInSeconds() {
            return ttl;
        }
    }


    @Bean
    KeyConfig codeKey() {
        return new SupportL1Config(CacheKeys.CODE_KEY, -1, workProperties.getUser().getCodeTimeOut()){

            @Override
            public boolean supportL1() {
                return true;
            }

            @Override
            public boolean supportL2() {
                return false;
            }
        };
    }


}
